package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.SMSUtils;
import com.example.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws Exception {
        String phone = user.getPhone();
        log.info("phone={}", phone);

        //生成4位数验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        log.info("code={}", code);

        //调用阿里云API发送短信
//        SMSUtils.sendMessage(phone, code);


        //将验证码存到session
        //session.setAttribute(phone, code);

        //将验证码存到redis，设置3分钟超时
        redisTemplate.opsForValue().set(phone, code, 3L, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }


    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){  //将json中的数据封装到map中
        log.info(map.toString());

        //获取提交的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //取出session中的验证码
        //String codeInSession = session.getAttribute(phone).toString();

        //取出redis中的验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);

        //进行对比
        if (!(code!=null && code.equals(codeInSession))){
            //失败
            return R.error("验证码错误");
        }

        //成功，则判断是否为新用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);

        //新用户则自动注册
        if (user == null){
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }

        //将用户Id存入session
        session.setAttribute("user", user.getId());

        //登录成功后，将redis中验证码删除
        redisTemplate.delete(phone);

        return R.success(user);
    }

}
